package com.admin.controller;

import java.util.Date;

import com.admin.model.Article;
import com.admin.util.Page;
import com.admin.util.UtilTools;

public class ArticleController extends BaseController {
	public static String TOARTICLE = "/article";
	// 首页列表
	public void index(){
		try {
			// 处理查询条件
			Article article = getModel(Article.class);
			String name = article.get("name");
			String aname = null;
			if(UtilTools.isNotNull(name)){
				aname = "name like '%"+ name +"%'";
			}
			Integer status = article.get("status");
			String astatus = null;
			if(UtilTools.isNotNull(status)){
				astatus = "status = '"+ status +"'";
			}
			// 处理分页参数
			Page<Article> page = new Page<Article>(getPara("pageCurrent"),getPara("pageSize"));
			page.setOrderField("sortx");
			page.setOrderDirection("asc");
			Article.dao.listByPage(new String[]{astatus,aname},page);
			setAttr("page",page);
			render("/jsp/article/index.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// 跳转到修改
	public void detail(){
		try {
			String id = getPara("id");
			Article article = Article.dao.getObject(Long.parseLong(id));
			setAttr("article", article);
			render("/jsp/article/add.jsp");
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.getMessage(), e);
		}
	}
	
	// 保存
	public void save() {
		try {
			Article article = getModel(Article.class);
			if (null == article.get("id")) {
				article.set("createTime",new Date());
				article.save();
			} else {
				article.update();
			}
			ajax(Status.success,TOARTICLE,true);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.getMessage(), e);
			ajax(Status.error,null,null);
		}
	}
	
	// 删除
	public void delete(){
		try {
			String[] ids = getParaValues("ids");
			boolean result = Article.dao.del(ids);
			if(result){
				ajax(Status.success,null,false);
			}else{
				ajax(Status.error,null,null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ajax(Status.error,null,null);
		}
	}
}
